<?php

    require_once 'DB.class.php';
    require_once 'getDistance.php';
    require_once 'doubleArraySort.php';
    
    $longitude = $_POST['longitude'];
    $latitude = $_POST['latitude'];
    
    
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    
    if(!$redis->exists('location')){
        $conn = DB::getInstance('localhost', 'root', 'root', 'wechat', 'utf8');
        
        $sql = "select name, address, longitude, latitude from location";
        $res = $conn->query($sql);
        $json = json_encode($res);
        $redis->set('location', $json);
    }
    
    $res = json_decode($redis->get('location'), true);
    
    $data = array();
    $i = 0;
    foreach($res as $val) {
        $data[$i] = $val;
        $data[$i]['distance'] = intval(getDistance($latitude, $longitude, $val['latitude'], $val['longitude'], 1));
        $i++;
    }
    
    $newData = doubleArraySort($data, 'distance');
    
    foreach($newData as $key => $val) {
        if($val['distance'] >= 1000) {
            $newData[$key]['distance'] = round($val['distance'] / 1000, 2) . '千米';
        }else{
            $newData[$key]['distance'] = $val['distance'] . '米';
        }
    }
    
    $result = json_encode($newData, JSON_UNESCAPED_UNICODE);
    $redis->set('location', $result);
    
    echo $result;
    




